package com.hanzhong.travel.service.impl;

import com.hanzhong.travel.entity.User;
import com.hanzhong.travel.mapper.UserMapper;
import com.hanzhong.travel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public User findByUsername(String username) {
        System.out.println("查询用户: " + username);
        User user = userMapper.findByUsername(username);
        System.out.println("查询结果: " + (user != null ? "找到用户" : "未找到用户"));
        if (user != null) {
            System.out.println("用户密码长度: " + user.getPassword().length());
        }
        return user;
    }
    
    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }
    
    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }
        
        // 密码加密
        String rawPassword = user.getPassword();
        String encodedPassword = passwordEncoder.encode(rawPassword);
        System.out.println("原始密码长度: " + rawPassword.length() + ", 加密后密码长度: " + encodedPassword.length());
        user.setPassword(encodedPassword);
        
        // 设置默认值
        user.setStatus(1); // 正常状态
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        
        return userMapper.insert(user) > 0;
    }
    
    @Override
    public boolean updateUser(User user) {
        // 设置更新时间
        user.setUpdateTime(new Date());
        
        return userMapper.update(user) > 0;
    }
    
    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            System.out.println("尝试登录用户: " + username);
            System.out.println("输入密码: " + password);
            System.out.println("数据库密码: " + user.getPassword());
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            System.out.println("密码匹配结果: " + matches);
            if (matches) {
                return user;
            }
        }
        return null;
    }
} 